package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class myTask {
    @Autowired
    private OrderMapper orderMapper;
    @Scheduled(cron = "0 0/1 * * * ?")
    public void ExpirationOrderTask() {
        //每分钟做一次定时任务
        try {
            log.info("开始执行定时任务：取消超时订单");
            //查找订单就是创建时间离现在超过15分钟并且订单状态是待支付的状态 status是1的的订单
            LocalDateTime time = LocalDateTime.now().minusMinutes(15);
            List<Orders> list = orderMapper.getByStatusForExpiration(Orders.PENDING_PAYMENT,time);
            if (!CollectionUtils.isEmpty(list)) {
                for (Orders orders : list) {
                        //更新订单状态为4
                        log.info("订单{}超时，准备取消", orders.getId());
                        orders.setStatus(Orders.CANCELLED);
                        orders.setCancelReason("支付超时");
                        orders.setCancelTime(LocalDateTime.now());
                        orderMapper.update(orders);

                }
            }
        } catch (Exception e) {
            log.error("执行取消超时订单任务时发生异常：", e);
        }
    }
    @Scheduled(cron = "0 0 1 * * ?")
    public void ProcessAtCertainTimeTask(){
        try {
            //我们要进行的是对于派送中的订单，在统一的凌晨一点进行处理修改订单状态为已完成 5
            //对日期函数处理也要熟悉
            log.info("开始进行定时任务：处理处于派送中的订单");
            List<Orders> list = orderMapper.getByStatusForExpiration(Orders.DELIVERY_IN_PROGRESS,LocalDateTime.now().minusHours(1));
            //把他们统一修改为已完成即可
            if (!CollectionUtils.isEmpty(list)) {
                for (Orders orders : list) {
                    orders.setStatus(Orders.COMPLETED);
                    orderMapper.update(orders);
                }
            }
        } catch (Exception e) {
            log.error("执行处理派送中订单任务时发生异常：", e);
        }
    }
}
